package org.budo.support.spring.web.interceptor.sessioncheck;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.method.HandlerMethod;

/**
 * @author lmw
 * @see org.budo.support.spring.web.interceptor.sessioncheck.SessionCheck
 */
public class SessionCheckInterceptor extends AbstractSessionCheckInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (null == handler || !(handler instanceof HandlerMethod)) {
            return true;
        }

        HandlerMethod handlerMethod = (HandlerMethod) handler;
        SessionCheck sessionCheck = handlerMethod.getMethodAnnotation(SessionCheck.class);
        if (null == sessionCheck) {
            return true;
        }

        Object sessionValue = request.getSession().getAttribute(this.getSessionKey());

        if (null != sessionValue) {
            return true;
        }

        // javax.servlet.forward.request_uri=/topic_save.json
        // javax.servlet.forward.context_path=
        // javax.servlet.forward.servlet_path=/topic_save.json

        request.getRequestDispatcher(this.getUnauthorizedUrl()).forward(request, response);
        return false;
    }
}
